import isPlainObject from './utils/isPlainObject';
import ActionTypes from './utils/actionTypes';

export default function createStore(reducer,preloadedState){ //通过createStore赋的初始值优先级比reducer里赋的高
    if(typeof reducer != 'function'){
        throw new Error('reducer必须是一个函数');
    }

    let currentReducer = reducer;
    let currentState = preloadedState;
    let currentListeners = []; //用来保存订阅的

    //返回当前状态
    function getState(){
        return currentState;
    }

    function dispatch(action){
        //action必须是一个纯对象，new Object new出来的or字面量创建出来的
        //函数new出来的不是，数组也不是
        if(!isPlainObject(action)){
            throw new Error('action必须是一个纯对象');
        }

        if(typeof action.type === 'undefined'){
            throw new Error('action的type属性不能是 undefined');
        }

        currentState = currentReducer(currentState, action);

        for(let i=0;i<currentListeners.length;++i){
            const listener = currentListeners[i];
            listener();
        }

        return action;
    }

    function subscribe(listener){
        let subscribed = true;
        currentListeners.push(listener);
        return function unsubscribe(){
            if(!subscribed) return;
            const i = currentListeners.indexOf(listener);
            currentListeners.splice(i, 1);
            subscribed = false;
        }
    }


    dispatch({type: ActionTypes.INIT}); //先派发一次，会走default，主要是为了以防是在reducer中赋的初始值

    return {
        getState
        ,dispatch
        ,subscribe
    }
}
